package lz4

import (
	"io/ioutil"
	"os"

	"github.com/pierrec/lz4"
)

// func: SaveLz4File(file string, data []byte) (err error)
// aim: lz4算法保存数据到文件

func SaveLz4File(file string, data []byte) (err error) {
	os.RemoveAll(file)
	f, err := os.Create(file + ".tmp")
	if err != nil {
		return
	}
	zw := lz4.NewWriter(f)
	zw.BlockMaxSize = 1024 * 1024
	zw.CompressionLevel = 0

	_, err = zw.Write(data)
	if err != nil {
		return
	}
	zw.Close()
	f.Close()
	if err != nil {
		return
	}

	path := file + ".tmp"
	err = os.Rename(path, file)
	return
}


// func: LoadLz4File(file string) (data []byte, err error)
// aim: LoadLz4File 从文件中加载

func LoadLz4File(file string) (data []byte, err error) {
	f, err := os.Open(file)
	if err != nil {
		return
	}
	defer f.Close()
	zr := lz4.NewReader(f)
	data, err = ioutil.ReadAll(zr)
	return
}
